package com.example.config;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局过滤器第一种写法
 */
@Configuration
public class GlobalGatewayFilterConfig {
    @Bean
    public GlobalFilter elapsedGlobalFilter(){
        return new GlobalFilter() {
            public Mono<Void> filter(final ServerWebExchange exchange, final GatewayFilterChain chain) {
                //调用请求之前统计时间
                final Long startTime = System.currentTimeMillis();
                return chain.filter(exchange).then(Mono.<Void>fromRunnable(new Runnable() {
                    public void run() {
                        //调用请求之后统计时间
                        Long endTime = System.currentTimeMillis();
                        System.out.println("Gloabl elapsedGlobalFilter"+
                                exchange.getRequest().getURI().getRawPath() + ", cost time : " + (endTime - startTime) + "ms");
                    }
                }));
            }
        };
    }
}
